package com.formiaomiao.demain.service.impl;

import com.formiaomiao.demain.dao.CommentDao;
import com.formiaomiao.demain.dao.DiscussDao;
import com.formiaomiao.demain.dao.UserDao;
import com.formiaomiao.demain.model.CommentBean;
import com.formiaomiao.demain.model.DiscussBean;
import com.formiaomiao.demain.model.Result;
import com.formiaomiao.demain.model.ResultData;
import com.formiaomiao.demain.service.CommentService;
import com.formiaomiao.demain.utils.ResultUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(value = "commentService")
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentDao commentDao;
    @Autowired
    DiscussDao discussDao;
    @Autowired
    UserDao userDao;

    @Transactional(value = "demain")
    @Override
    public Result<String> InsertComment(CommentBean commentBean) {
        if (commentDao.InsertComment(commentBean) == 0) {
            return ResultUtil.error(400, "评论失败");
        } else {
            return ResultUtil.success("评论成功");
        }
    }

    @Transactional(value = "demain")
    @Override
    public Result<String> DeleteComment(CommentBean commentBean) {
        if (commentDao.DeleteComment(commentBean) == 0) {
            return ResultUtil.error(400, "删除失败");
        } else {
            DiscussBean discussBean = new DiscussBean();
            discussBean.setComid(commentBean.getComid());
            if(discussDao.SelectDiscuss(commentBean.getComid()).size()>0){
                if (discussDao.DeleteAllDuscuss(discussBean) == 0) {
                    return ResultUtil.error(400, "删除失败");
                }
            }
            return ResultUtil.success("删除成功");
        }
    }

    @Override
    public Result<CommentBean> SelectComment(String topicid, int pageNum, int pageSize) {
        if (commentDao.SelectComment(topicid).size() == 0) {
            return ResultUtil.error(400, "暂没有评论信息");
        } else if (commentDao.SelectComment(topicid).size() > 0) {
            PageHelper.startPage(pageNum, pageSize);
            List<CommentBean> list = commentDao.SelectComment(topicid);
            int discusscount = 0;
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setUserBean(userDao.selectUser(list.get(i).getFromuid()));
                for (int j = 0; j < discussDao.SelectDiscuss(list.get(i).getComid()).size(); j++) {
                    discusscount += 1;
                }
                list.get(i).setDiscusscount(discusscount);
            }
            ResultData result = new ResultData(pageNum, pageSize, list);
            return ResultUtil.success(result);
        } else {
            return ResultUtil.error(400, "获取失败");
        }
    }
}
